package ch.elca.training.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ch.elca.training.dao.ProjectDao;
import ch.elca.training.dom.Project;
import ch.elca.training.dto.ProjectCriterionDto;
import ch.elca.training.exception.AtLeastOneCriterionMustBePutIntoSystemException;
import ch.elca.training.service.ProjectService;

@Service("projectService")
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	private ProjectDao projectDao;

	@Override
	public void createProject(Project project) {
		projectDao.saveOrUpdate(project);

	}

	@Override
	public void editProject(Project project) {

	}

	@Override
	public List<Project> searchProject(ProjectCriterionDto criterion) throws AtLeastOneCriterionMustBePutIntoSystemException {

		Integer projectNumber = criterion.getNumber();
		String customer = criterion.getCustomer();
		String projectName = criterion.getName();
		String status = criterion.getStatus();
		
		if(projectNumber == null && customer == null && projectName == null && status == null) {
			throw new AtLeastOneCriterionMustBePutIntoSystemException("At least one criterion must be put into system for searching");
		}
		List<Project> projects = projectDao.getAll();
		List<Project> result = new ArrayList<Project>();

		for (Project project : projects) {
			if ((project.getCustomer().equals(customer) || customer == null)
					&& (project.getProjectName().equals(projectName) || projectName == null)
					&& (project.getProjectNumber().equals(projectNumber) || projectNumber == null)
					&& (project.getStatus().equals(status) || status == null)) {
				result.add(project);
			}
		}
		return result;
	}

	@Override
	public void deleteProjects(List<Project> projects) {
		projectDao.delete(projects);
	}

	@Override
	public void saveProject(Project project) {
		projectDao.saveOrUpdate(project);
	}

	@Override
	public Project findById(long id) {
		List<Project> projects = projectDao.getAll();
		for(Project project : projects) {
			if(project.getId() == id){
				return project;
			}
		}
		return null;
	}

}
